package com.hyk.entity.response;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.hyk.entity.User;
import com.hyk.service.IUserService;
import com.hyk.utils.MD5Utils;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: chen
 * @Date: 2021/3/22 9:20 AM
 * @Version 1.0
 */
@Data
@RequiredArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class UserImportListener extends AnalysisEventListener<UserExcel> {

    /**
     * 默认每隔3000条存储数据库
     */
    private int batchCount = 3000;
    /**
     * 缓存的数据列表
     */
    private List<UserExcel> list = new ArrayList<>();
    /**
     * 用户service
     */
    private final IUserService userService;

    @Override
    public void invoke(UserExcel data, AnalysisContext context) {
        list.add(data);
        // 达到BATCH_COUNT，则调用importer方法入库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= batchCount) {
            // 调用importer方法
            userService.saveBatch(tranfer());
            // 存储完成清理list
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 调用importer方法
        List<User> users = tranfer();
        userService.saveBatch(users);
        // 存储完成清理list
        list.clear();
    }

    private List<User> tranfer() {
        return list.stream().map(userExcel -> {
            User user = new User();
            BeanUtils.copyProperties(userExcel, user);
            user.setPassword(MD5Utils.encode("123456"));
            return user;
        }).collect(Collectors.toList());
    }
}